import express from "express"
import path from "path"
import fs from "fs"
import uuid from "node-uuid"
import sendEmail from "./sendEmail"
let urls = path.join(__dirname,"./public")
let app = express()
app.listen(3000,()=>{
    console.log("服务器启动了!!!~");
})
app.get("/hom.html",(req,res,next)=>{
    console.log(req.query);
    let cook = req.get("Cookie")||""
    console.log(cook);
    let arr = cook.split("; ")
    let brr = JSON.parse(fs.readFileSync(path.join(__dirname,"./public/user.json")))
    let obj = {}
    arr.forEach(item=>{
        obj[item.slice(0,item.indexOf("="))]=item.slice(item.indexOf("=")+1)
    })
    let cok = obj["cok"]
   console.log(brr.find(item=>{return item === cok}) );
    if(brr.find(item=>{return item === cok})){
       
        sendEmail(req,res)
        console.log("登录成功");
        next()
    }else{
        console.log("未登录");
       
        res.redirect("/index.html")
    }
  
})

app.use(
    express.static(urls)

)
app.get("/login",(req,res)=>{
    let {user,pass} = req.query
    console.log(user,pass);
    let arr =JSON.parse( fs.readFileSync(path.join(__dirname,"./public/json.json")))
    let a = arr.find(item=>{return item.user === user})
    console.log(a);
    if(a){
        if (a.pass === pass) {
            let str = uuid.v1();
            let brr = JSON.parse( fs.readFileSync(path.join(__dirname,"./public/user.json")),"utf-8")
            brr.push(str)
            fs.writeFileSync(path.join(__dirname,"./public/user.json"),JSON.stringify(brr),"utf-8")
            //发送邮件处理
            res.cookie("cok",str)
            res.send({
                type:"001"
            })

        }else{
            console.log("密码错误");
            res.send({
                type:"002"
            })
        }
    }else{
        console.log("账号不存在");
        res.send({
            type:"003"
        })
    }
})
app.use(
    express.json()
)
app.post("/zhu",(req,res,next)=>{
    console.log(123456888888888);
    console.log(req.body);
})
